package com.kingdee.pda.ui.scan_inwarehouse;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.MusicUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.Api;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.out_check.OutCheckActivity;
import com.kingdee.pda.ui.sn_query_edit.ItemSNInfoVo;
import com.kingdee.pda.util.CommonUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;

/**
 * 扫描收货
 * Created by dlj
 * DATE 2021/11/8
 * TIME 10:20
 */
public class ScanReceiveOrderActivity extends BaseTitleActivity implements View.OnKeyListener {
    @BindView(R.id.et_orderNo)
    EditText et_orderNo;
    @BindView(R.id.btn_confirm)
    Button btn_confirm;
    @BindView(R.id.btn_confirm_1)
    Button btn_confirm_1;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private List<ScanReceiveOrderBean.AsnListBean> lists = new ArrayList<>();
    private ScanReceiveOrderAdapter adapter;
    private List<ScanReceiveOrderBean.AsnLinkAfterOrderSnVo> linkAfterOrderSnList;
    private boolean isSnboolean;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, ScanReceiveOrderActivity.class));
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(et_orderNo.getText().toString())) {
            et_orderNo.setText("");
            lists.clear();
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_receive);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("扫描收货");

        setEditTextScannerEvents(et_orderNo, this);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ScanReceiveOrderAdapter(this, lists);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String number = et_orderNo.getText().toString();
                if (lists.size() > 0 && !TextUtils.isEmpty(number)) {
                    //进入收货界面之前，将所有ASN单中的同货主同sku的数量进行合并
                    List<ScanReceiveShowDetailBean> detailBeans = mergeSameOwnerSku();
                    ScanReceiveOperationActivity.actionStart(ScanReceiveOrderActivity.this, detailBeans, linkAfterOrderSnList, false, lists.get(0).getTypein(), isSnboolean);
                } else {
                    SpeakUtils.speakWithToast(ScanReceiveOrderActivity.this, "请先输入单号并确认！", true, false);
                    CommonUtil.requestFocusAndClearText(et_orderNo);
                }
            }
        });

        btn_confirm_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String number = et_orderNo.getText().toString();
                if (lists.size() > 0 && !TextUtils.isEmpty(number)) {
                    //进入收货界面之前，将所有ASN单中的同货主同sku的数量进行合并
                    List<ScanReceiveShowDetailBean> detailBeans = mergeSameOwnerSku();
                    ScanReceiveOperationActivity.actionStart(ScanReceiveOrderActivity.this, detailBeans, linkAfterOrderSnList, true, lists.get(0).getTypein(), isSnboolean);
                } else {
                    SpeakUtils.speakWithToast(ScanReceiveOrderActivity.this, "请先输入单号并确认！", true, false);
                    CommonUtil.requestFocusAndClearText(et_orderNo);
                }
            }
        });

        CommonUtil.requestFocusAndNoClearText(et_orderNo);
    }

    /**
     * //进入收货界面之前，将所有ASN单中的同货主同sku的数量进行合并
     */
    private List<ScanReceiveShowDetailBean> mergeSameOwnerSku() {
        //创建一个map去合并，key为 货主+sku 纬度
        HashMap<String, ScanReceiveShowDetailBean> detailMap = new HashMap<>();
        for (ScanReceiveOrderBean.AsnListBean asnBean : lists) {//遍历所有asn单
            for (ScanReceiveOrderBean.AsnListBean.DetailBean detailbean : asnBean.getDetail()) {//遍历asn单中所有sku
                detailbean.setScanbillno(asnBean.getBillno());
                detailbean.setId(asnBean.getBillid());
                String key = detailbean.getSkuid() + detailbean.getOwnerid();
                if (detailMap.containsKey(key)) {//如果map中已有此货主+sku，则叠加数量，增加asn单号，并且将此sku详情行加入detailBeanList
                    ScanReceiveShowDetailBean containsBean = detailMap.get(key);

                    containsBean.setPalnqty(containsBean.getPalnqty() + detailbean.getPalnqty());
                    containsBean.setReceiptedqty(containsBean.getReceiptedqty() + detailbean.getReceiptedqty());
                    containsBean.setScannedqty(containsBean.getScannedqty() + detailbean.getScannedqty());//一般已扫数量应该是0，保险起见也加上

                    Set<String> billnos = containsBean.getBillnos();//添加单号集合
                    billnos.add(asnBean.getBillno());
                    List<ScanReceiveOrderBean.AsnListBean.DetailBean> detailBeanList = containsBean.getDetailBeanList();
                    detailBeanList.add(detailbean);
                } else {//如果此货主+sku还未存过，则创建一个新的ScanReceiveShowDetailBean加入
                    ScanReceiveShowDetailBean scanReceiveShowDetailBean = new ScanReceiveShowDetailBean();
                    HashSet<String> billnos = new HashSet<>();
                    billnos.add(asnBean.getBillno());
                    scanReceiveShowDetailBean.setBillnos(billnos);
                    scanReceiveShowDetailBean.setOwnername(detailbean.getOwnername());
                    scanReceiveShowDetailBean.setOwnerid(detailbean.getOwnerid());
                    scanReceiveShowDetailBean.setSkuname(detailbean.getSkuname());
                    scanReceiveShowDetailBean.setSpucode(detailbean.getSpucode());
                    scanReceiveShowDetailBean.setSpuname(detailbean.getSpuname());
                    scanReceiveShowDetailBean.setPalnqty(detailbean.getPalnqty());
                    scanReceiveShowDetailBean.setReceiptedqty(detailbean.getReceiptedqty());
                    scanReceiveShowDetailBean.setScannedqty(detailbean.getScannedqty());
                    scanReceiveShowDetailBean.setSn(detailbean.getSn());
                    scanReceiveShowDetailBean.setSkuid(detailbean.getSkuid());
                    scanReceiveShowDetailBean.setSkubarcode(detailbean.getSkubarcode());

                    List<ScanReceiveOrderBean.AsnListBean.DetailBean> addDetailDeans = new ArrayList<>();
                    addDetailDeans.add(detailbean);
                    scanReceiveShowDetailBean.setDetailBeanList(addDetailDeans);
                    detailMap.put(key, scanReceiveShowDetailBean);
                }
            }
        }

        Collection<ScanReceiveShowDetailBean> values = detailMap.values();
        for (ScanReceiveShowDetailBean scanReceiveShowDetailBean : values) {
            //按待收数量进行排序
            Collections.sort(scanReceiveShowDetailBean.getDetailBeanList(), new Comparator<ScanReceiveOrderBean.AsnListBean.DetailBean>() {
                public int compare(ScanReceiveOrderBean.AsnListBean.DetailBean e1, ScanReceiveOrderBean.AsnListBean.DetailBean e2) {
                    int a = (e1.getPalnqty() - e1.getReceiptedqty()) - (e2.getPalnqty() - e2.getReceiptedqty());
                    return a;
                }
            });
        }
        return new ArrayList<>(values);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (TextUtils.isEmpty(input)) return false;
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.getAction() == KeyEvent.ACTION_UP) {
            if (v.getId() == R.id.et_orderNo) {

//                HashMap<String, Object> map = new HashMap<>();
//                map.put("snno", input);
//                map.put("warehouse", getCurrentWarehouse().getId());
//                pdaSnQuery(map);
                scanOrder(input);
                return true;
            }
        }
        return false;
    }


//    private void pdaSnQuery(HashMap<String, Object> map) {
//        MyObserver<List<ItemSNInfoVo>> myObserver = new MyObserver<List<ItemSNInfoVo>>(ScanReceiveOrderActivity.this) {
//            @Override
//            public void onSuccess(BaseResponse<List<ItemSNInfoVo>> result) {
//                Log.d("pdaQuerySnInfo",result.data.toString());
//            }
//
//            @Override
//            public void onFailure(BaseResponse result, String msg) {
////                SpeakUtils.speakWithToast(context, msg, false, false);
//                Log.d("pdaQuerySnInfo",msg);
//
//            }
//        };
//        HttpUtils.request(Api.class)
//                .pdaQuerySnInfo(ConstantUtil.PDA_SN_QUERY, map)
//                .compose(RxHelper.observableIO2Main(ScanReceiveOrderActivity.this))
//                .subscribe(myObserver);
//    }


    private void scanOrder(String orderNo) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("scanbillno", orderNo);

        MyObserver<ScanReceiveOrderBean> myObserver = new MyObserver<ScanReceiveOrderBean>(this) {
            @Override
            public void onSuccess(BaseResponse<ScanReceiveOrderBean> result) {
                linkAfterOrderSnList = result.data.getLinkAfterOrderSnList();
                MusicUtils.getInstance().playSuccess(2);

                if (result.data.getAsnList().size() > 0 &&  !result.data.getAsnList().get(0).getWarehouseId().equals(getCurrentWarehouse().getId() + "")) {
                    SpeakUtils.speakWithToast(ScanReceiveOrderActivity.this, "此单不属于该仓库！", true, false);
                    CommonUtil.requestFocusAndClearText(et_orderNo);
                    return;
                }

                isSnboolean = result.data.isSnboolean();
                lists.clear();
                lists.addAll(result.data.getAsnList());
                adapter.notifyDataSetChanged();
                if (lists.size() > 0) {
                    btn_confirm.setEnabled(true);
                    btn_confirm_1.setEnabled(true);
                }

            }

            @Override
            public void onFailure(BaseResponse result, String msg) {
                SpeakUtils.speakWithToast(ScanReceiveOrderActivity.this, msg, true, false);
                btn_confirm.setEnabled(false);
                btn_confirm_1.setEnabled(false);
                CommonUtil.requestFocusAndClearText(et_orderNo);
            }
        };
        HttpUtils.request(Api.class)
                .scanReceiptQuery(ConstantUtil.SCANRECEIPT_QUERY, map)
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(myObserver);
    }
}
